package com.xianghualin.service.impl;

import com.xianghualin.mapper.PostMapper;
import com.xianghualin.mapper.ReplyMapper;
import com.xianghualin.pojo.Post;
import com.xianghualin.pojo.Reply;
import com.xianghualin.service.ReplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.List;

/**
 * ReplyServiceImpl
 */
@Service
public class ReplyServiceImpl implements ReplyService {
    private final ReplyMapper replyMapper;
    private final PostMapper postMapper;

    @Autowired
    public ReplyServiceImpl(ReplyMapper replyMapper, PostMapper postMapper) {
        this.replyMapper = replyMapper;
        this.postMapper = postMapper;
    }

    @Override
    public void addReply(Reply reply) {
        // 更新post信息
        Reply dbReply = reply;
        int postId = reply.getReplyPostId();
        Post post = postMapper.findPostByPostId(postId);
        post.setPostReplyCount(post.getPostReplyCount() + 1);
        postMapper.updatePostByPost(post);

        // 添加回复
        dbReply.setReplyCreateTime(new Timestamp(System.currentTimeMillis()));
        replyMapper.addReply(dbReply);
    }

    @Override
    public List<Reply> listReplyByPostId(int replyPostId) {
        return replyMapper.listReplyByPostId(replyPostId);
    }

    @Override
    public void deleteReply(int replyId) {
        // 更新post信息
        Reply reply = replyMapper.findReplyByReplyId(replyId);
        Post post = postMapper.findPostByPostId(reply.getReplyPostId());
        post.setPostReplyCount(post.getPostReplyCount() - 1);
        postMapper.updatePostByPost(post);

        // 删除回复
        replyMapper.deleteReplyById(replyId);
    }
}